package org.je.database;

import java.util.ArrayList;
import java.util.List;

import org.je.database.impl.DataSource;
import org.je.database.impl.ExecutorGroup;
import org.je.database.impl.SqlExecutor;
import org.je.database.impl.StaticConfig;
import org.je.util.StringUtil;

/**
 * @author fanyifeng
 */
public class DbUtil
{

	public static SqlExecutor src(String id) {
		init();
		for (ExecutorGroup g : list) {
			if (StringUtil.equals(g.id, id)) {
				return g.getExecutor();
			}
		}
		throw new RuntimeException("cant-found-this-datasource[" + id + "]");
	}

	public static SqlExecutor src(int i) {
		init();
		return list.get(i).getExecutor();
	}

	public static SqlExecutor src() {
		return src(0);
	}

	/** private method **/

	private final static List<ExecutorGroup>	list		= new ArrayList<ExecutorGroup>();
	private static volatile boolean				isInit		= false;
	private static final Object					initLock	= new Object();

	private static void init() {
		if (isInit)
			return;
		synchronized(initLock) {
			if (isInit)
				return;
			doInit();
			isInit = true;
		}
	}

	private static void doInit() {
		for (int i = 0; i < StaticConfig.sizeOfDataSource(); ++i) {
			DataSource ds = StaticConfig.getDataSource(i);
			list.add(new ExecutorGroup(ds));
		}
	}
}
